package com.she.iiicoursecenter.eventmanager;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.TimeZone;
import java.util.Map.Entry;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.she.component.util.md5.MD5;
import com.she.iiicoursecenter.R;
import com.she.iiicoursecenter.iiiApplication;
import com.she.iiicoursecenter.event.base.Event;
import com.she.iiicoursecenter.event.connect.bean.GetContentBean;
import com.she.iiicoursecenter.event.connect.bean.GetContentListBean;
import com.she.iiicoursecenter.event.connect.bean.GetItemListBean;
import com.she.iiicoursecenter.event.connect.bean.GetMakeBean;
import com.she.iiicoursecenter.event.connect.bean.GetMsgBean;
import com.she.iiicoursecenter.event.connect.bean.GetTokenBean;
import com.she.iiicoursecenter.event.connect.bean.HideMakeExpireBean;
import com.she.iiicoursecenter.event.connect.bean.SearchConditionedBean;
import com.she.iiicoursecenter.event.connect.bean.SearchContentBean;
import com.she.iiicoursecenter.event.connect.bean.UpdMakeBean;
import com.she.iiicoursecenter.event.connect.bean.getMsgCountBean;
import com.she.iiicoursecenter.event.connect.event.GetContentEvent;
import com.she.iiicoursecenter.event.connect.event.GetContentListEvent;
import com.she.iiicoursecenter.event.connect.event.GetItemListEvent;
import com.she.iiicoursecenter.event.connect.event.GetMakeEvent;
import com.she.iiicoursecenter.event.connect.event.GetMsgEvent;
import com.she.iiicoursecenter.event.connect.event.GetTokenEvent;
import com.she.iiicoursecenter.event.connect.event.HideMakeExpireEvent;
import com.she.iiicoursecenter.event.connect.event.SearchConditionedEvent;
import com.she.iiicoursecenter.event.connect.event.SearchContentEvent;
import com.she.iiicoursecenter.event.connect.event.SeverTimeEvent;
import com.she.iiicoursecenter.event.connect.event.UpdMakeEvent;
import com.she.iiicoursecenter.event.connect.event.getMsgCountEvent;
import com.she.iiicoursecenter.event.iface.IEventCallback;

import android.content.Context;
import android.util.Log;

public class KenEventManager {

//	private Handler mHandler = new Handler();
	
	// Keep Application Context
	private Context mContext = null;
	// Callback Registration Map
	private HashMap<String, List<IEventCallback>> mListenerMap  = new HashMap<String, List<IEventCallback>>();
	// 還有前置事項未完成的會進入Pending Map 
	private HashMap<String, Event> mPendingMap   = new HashMap<String, Event>();
	// 正在執行的會進入Executing Map
	private HashMap<String, Event> mExecutingMap = new HashMap<String, Event>();
	// Thread Pool
	private Executor mGeneralPool = Executors.newFixedThreadPool(50);

	
	/***************
	 * Constructor *
	 ***************/
	private KenEventManager() {}
	
	// Single Instance of EbookletEventManager
	private static KenEventManager mAPIManager = null;
	
	public static KenEventManager getInstance() {
		if(mAPIManager == null) mAPIManager = new KenEventManager();
		return mAPIManager;
	}
	
	// Should be called right after APIManager is created
	public void init(Context context) {
		if(mContext == null) mContext = context.getApplicationContext();
	}

		
	/********************
	 * Public Functions *
	 ********************/
	
	public boolean queryEvent(String signature) {
		if(mExecutingMap.containsKey(signature) || mPendingMap.containsKey(signature))
			return true;
		else
			return false;
	}
	
	public void registerListener(final String signature, final IEventCallback callback) {
		if(callback == null) return;
		mGeneralPool.execute(new Runnable() {
			public void run() {
				synchronized(mListenerMap) {
					if(mListenerMap.containsKey(signature)) {
						// 有的話就把Callback List拿出來加進去
						mListenerMap.get(signature).add(callback);
					}
					else {
						// 沒有的話就新增進去Map
						List<IEventCallback> iCallbacks = new ArrayList<IEventCallback>();
						iCallbacks.add(callback);
						mListenerMap.put(signature, iCallbacks);
					}
				}
			}
		});
	}
	
	public void unregisterListener(final IEventCallback callback) {
		if(callback == null) return;
		mGeneralPool.execute(new Runnable() {
			public void run() {
				synchronized(mListenerMap) {
					Iterator<Entry<String, List<IEventCallback>>> it = mListenerMap.entrySet().iterator();
					while(it.hasNext()) {
						// 把所有這個callback給移除
						List<IEventCallback> list = it.next().getValue();
						list.remove(callback);
					}
				}
			}
		});
	}
	
	public void cancel(final String signature) {
		mGeneralPool.execute(new Runnable() {
			public void run() {
				synchronized(mPendingMap) {
					synchronized(mExecutingMap) {
						// 解除Pending裡的這個事件
						mPendingMap.remove(signature);
						// 解除Executing裡的這個事件
						mExecutingMap.remove(signature);
					}
				}
			}
		});
	}
	
	public void clearExecutingMap() {
		synchronized (mExecutingMap) {
			mExecutingMap.clear();
		}
	}
	
	public void execute(final Event event) {
		mGeneralPool.execute(new Runnable() {
			public void run() {
				synchronized(mPendingMap) {
					synchronized(mExecutingMap) {
						if(mExecutingMap.containsKey(event.getSignature())) {
							// 如果ExecutingMap裡有 -> 把event融入ExecutingMap裡的該事件(event就可以不用理它了)
							Event executingEvent = mExecutingMap.get(event.getSignature());
							if(executingEvent != null) {
								// 把SubEvent黏上
								executingEvent.addSubEvents(event.getSubEvents());
								// 把Callback黏上
								executingEvent.addCallbacks(event.getCallbacks());
							}
						}
						else {
							// 如果PendingMap裡有
							if(mPendingMap.containsKey(event.getSignature())) {
								// 拿出來PendingMap裡的來Merge到自己
								Event pendingEvent = mPendingMap.get(event.getSignature());
								// 插入SubEvents
								event.addSubEvents(pendingEvent.getSubEvents());
								// 插入Callbacks
								event.addCallbacks(pendingEvent.getCallbacks());
								// PendingMap裡的就可以拿掉惹
								mPendingMap.remove(event.getSignature());
							} 
							// 把Event插到ExecutingMap裡
							mExecutingMap.put(event.getSignature(), event);
							
							/************************
							 * 根據是屬於哪一種Event去執行該事件的行為
							 * 例如 : 啟動連網Thread
							 * if(event instanceof DownloadEvent) {
									..........................................
									notifyResult(event, object, true, false);
							   }
							   else if(event instanceof DownloadImageEvent) {
							   		..........................................
							   		notifyResult(event, object, true, true);
							   else {
							   		notifyResult(event, null, true, false);
							   }
							 * **************************/
							
							//TODO EVENT
							
							/**serveryTime查詢event*/
							if (event instanceof SeverTimeEvent) {
								
								long data = 0;
							    try
							    {
							    	String strResult="";					    	
							    	String urlString=((SeverTimeEvent) event).getPath();

										HttpURLConnection conn = (HttpURLConnection) new URL(urlString).openConnection();
							        	// 設定Timeout時間
							        	conn.setConnectTimeout(30000);
							        	conn.setReadTimeout(30000);
							        	conn.setRequestMethod("POST");
							        	// Setup
							        	conn.setUseCaches (false); 
							        	conn.setDoOutput(true); 
							        	conn.setDoInput(true);
							        	/*輸入參數*/
//							        	OutputStream out = conn.getOutputStream(); 
//							        	String strPostData = "sn="+ String.valueOf(PersonalBean.getInstance().getChtsn()) + "&type=1&check="+genCheckCode(String.valueOf(PersonalBean.getInstance().getChtsn()));
//							        	out.write(strPostData.getBytes());  
////							        	Log.d("ken", "check "+check);
//							        	Log.d("ken", "個人優惠果實內容查詢rs "+strPostData);
//							        	out.close(); 
							        	
							        	//当正确响应时处理数据
							        	StringBuffer sb = new StringBuffer();
							        	String readLine;
							        	BufferedReader responseReader;
							        	//处理响应流，必须与服务器响应流输出的编码一致
							        	
							        	responseReader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
						    			String line = null; 
						    			StringBuilder stringBuilder = new StringBuilder();
						    			while((line = responseReader.readLine()) != null) {
						    				stringBuilder.append(line);
						    			}
							        	strResult = stringBuilder.toString();
//							        	Log.d("ken", "SeverTimeEvent  "+strResult);
							        	conn.disconnect();
							    	
							        	JSONObject jsonResponse = new JSONObject(strResult); 
							        	data = jsonResponse.getLong("SERVER_TIME");
							    	
//							    	/* 產生SAXParser物件 */ 
//							    	SAXParserFactory spf = SAXParserFactory.newInstance(); 
//							    	SAXParser sp = spf.newSAXParser(); 
//							    	/* 產生XMLReader物件 */ 
//							    	XMLReader xr = sp.getXMLReader(); 
//							    	/* 設定自定義的MyHandler給XMLReader */ 
////							    	ServerTimeXMLHandler myExampleHandler = new ServerTimeXMLHandler(); 
//							    	xr.setContentHandler(myExampleHandler);     
//							    	/* 解析XML */
//							    	xr.parse(new InputSource(new StringReader(strResult)));
//							    	/* 取得RSS標題與內容列表 */
//							    	data =myExampleHandler.getParsedData(); 
							    	
							    	if (data > 0) {
										long serverTime = (data * 1000) ; 
										long localTimeInGMT = new Date().getTime() + (new Date().getTimezoneOffset()*60*1000);
										long offset = serverTime-localTimeInGMT;
										setServerTimeOffset(offset);
									}
							    	
							    	notifyResult(event, data, true, false);
							    }
							    catch (Exception e)
							    { 
							      	notifyResult(event, data, false, false);
							    }
							}
							
							/**課程系列查詢event*/
							if (event instanceof GetItemListEvent) {
								
								List<GetItemListBean> data = new ArrayList<GetItemListBean>();
						    	GetItemListBean temp1 = new GetItemListBean();
						    	temp1.setItemId(111);
					    		temp1.setName("單機課程1");
						    	GetItemListBean temp2 = new GetItemListBean();
						    	temp2.setItemId(222);
					    		temp2.setName("單機課程2");
						    	GetItemListBean temp3 = new GetItemListBean();
						    	temp3.setItemId(333);
					    		temp3.setName("單機課程3");
						    	
					    		data.add(temp1);
					    		data.add(temp2);
					    		data.add(temp3);
							    try
							    {
							    	String strResult="";					    	
							    	String urlString=((GetItemListEvent) event).getPath();

										HttpURLConnection conn = (HttpURLConnection) new URL(urlString).openConnection();
							        	// 設定Timeout時間
							        	conn.setConnectTimeout(30000);
							        	conn.setReadTimeout(30000);
							        	conn.setRequestMethod("POST");
							        	// Setup
							        	conn.setUseCaches (false); 
							        	conn.setDoOutput(true); 
							        	conn.setDoInput(true);
							        	OutputStream out = conn.getOutputStream();
							        	String strPostData = "device=android&ver="+((iiiApplication)mContext).VER +"&checkCode="+genCheckCode("mic");
										out.write(strPostData.getBytes());
										out.close();
//										Log.d("ken", "strPostData" + strPostData);
							        	//当正确响应时处理数据
//							        	StringBuffer sb = new StringBuffer();
//							        	String readLine;
							        	BufferedReader responseReader;
							        	//处理响应流，必须与服务器响应流输出的编码一致
							        	
							        	responseReader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
						    			String line = null; 
						    			StringBuilder stringBuilder = new StringBuilder();
						    			while((line = responseReader.readLine()) != null) {
						    				stringBuilder.append(line);
						    			}
							        	strResult = stringBuilder.toString();
//							        	Log.d("ken", "GetItemListEvent  "+strResult);
							        	conn.disconnect();
							        	
							        	int result = new JSONObject(strResult).getInt("result");
							        	String message = new JSONObject(strResult).getString("message"); 
							        	JSONArray jsonResponse = new JSONObject(strResult).getJSONArray("list");
							    	// test only
							    	for (int i = 0; i < jsonResponse.length(); i++) {
							    		JSONObject jsonObj = (JSONObject)jsonResponse.opt(i);
							    		GetItemListBean temp = new GetItemListBean();
							    		temp.setMessage(message);
							    		temp.setResult(result);
							    		temp.setItemId(jsonObj.getInt("item_id"));
							    		temp.setName(jsonObj.getString("name"));
//							    		temp.setTimeOnline(jsonObj.getLong("time_online"));
//							    		temp.setTimeOffline(jsonObj.getLong("time_offline"));
//							    		temp.setTimeLastmodify(jsonObj.getLong("time_lastmodify"));
							    		data.add(temp);
									}
						    		
							    	notifyResult(event, data, true, false);
							    }
							    catch (Exception e)
							    { 
							      	notifyResult(event, data, false, false);
							    }
							}
							
							/**課程內容清單查詢event*/
							if (event instanceof GetContentListEvent) {
								
								List<GetContentListBean> data = new ArrayList<GetContentListBean>();
								
								GetContentListBean temp1 = new GetContentListBean();
					    		temp1.setContentId(111);
					    		temp1.setContentName("第二層-1");
					    		temp1.setItemId(123);
					    		temp1.setItemName("第二層-1");
					    		data.add(temp1);
					    		GetContentListBean temp2 = new GetContentListBean();
					    		temp2.setContentId(222);
					    		temp2.setContentName("第二層-1");
					    		temp2.setItemId(456);
					    		temp2.setItemName("第二層-1");
					    		data.add(temp2);
							    try
							    {
							    	String strResult="";					    	
							    	String urlString=((GetContentListEvent) event).getPath();

										HttpURLConnection conn = (HttpURLConnection) new URL(urlString).openConnection();
							        	// 設定Timeout時間
							        	conn.setConnectTimeout(30000);
							        	conn.setReadTimeout(30000);
							        	conn.setRequestMethod("POST");
							        	// Setup
							        	conn.setUseCaches (false); 
							        	conn.setDoOutput(true); 
							        	conn.setDoInput(true);
							        	OutputStream out = conn.getOutputStream();
							        	String strPostData = "device=android&ver="+((iiiApplication)mContext).VER +"&checkCode="+genCheckCode("mic"+((GetContentListEvent) event).getItemId()) + "&item_id=" +((GetContentListEvent) event).getItemId();
										out.write(strPostData.getBytes());
										out.close();
//										Log.d("ken", "strPostData" + strPostData);
							        	//当正确响应时处理数据
//							        	StringBuffer sb = new StringBuffer();
//							        	String readLine;
							        	BufferedReader responseReader;
							        	//处理响应流，必须与服务器响应流输出的编码一致
							        	
							        	responseReader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
						    			String line = null; 
						    			StringBuilder stringBuilder = new StringBuilder();
						    			while((line = responseReader.readLine()) != null) {
						    				stringBuilder.append(line);
						    			}
							        	strResult = stringBuilder.toString();
//							        	Log.d("ken", "GetContentListEvent  "+strResult);
							        	conn.disconnect();
							        	
							        	int result = new JSONObject(strResult).getInt("result");
							        	String message = new JSONObject(strResult).getString("message"); 
							        	int itemId = new JSONObject(strResult).getInt("item_id");
							        	String itemName = new JSONObject(strResult).getString("item_name"); 
							        	JSONArray jsonResponse = new JSONObject(strResult).getJSONArray("list");
							    	// test only
							    	for (int i = 0; i < jsonResponse.length(); i++) {
							    		JSONObject jsonObj = (JSONObject)jsonResponse.opt(i);
							    		GetContentListBean temp = new GetContentListBean();
							    		temp.setMessage(message);
							    		temp.setResult(result);
							    		temp.setContentId(jsonObj.getInt("content_id"));
							    		temp.setContentName(jsonObj.getString("content_name"));
							    		temp.setItemId(itemId);
							    		temp.setItemName(itemName);
							    		data.add(temp);
									}
							    	
							    	notifyResult(event, data, true, false);
							    }
							    catch (Exception e)
							    { 
							      	notifyResult(event, data, false, false);
							    }
							}
							
							/**課程內容查詢event*/
							if (event instanceof GetContentEvent) {
								
								GetContentBean data = new GetContentBean();
								data.setResult(000);
								data.setItemId(123);
						    	data.setCode("code");
						    	data.setName("test");
						    	data.setTotle(40);
						    	data.setRemain(5);
						    	data.setHour(100);
						    	data.setExpense(5000);
						    	data.setDateStart(1294567890);
						    	data.setDateEnd(1594578990);
						    	data.setTimeSlot("1,2,3,4,5");
						    	data.setTimeStart("08:00");
						    	data.setTimeEnd("17:00");
						    	data.setLocation("台北");
						    	data.setTel("09XXXXXXXX");
						    	data.setObject("老人");
						    	data.setObjective("活更久");
						    	data.setOutline("養生大法");
						    	data.setIntrodution("養生大法!養生大法!");
						    	data.setRemark("要有錢有閒");
						    	data.setPic("http://upload.wikimedia.org/wikipedia/commons/thumb/0/0f/Grosser_Panda.JPG/320px-Grosser_Panda.JPG");
						    	data.setContentId(123);
								
							    try
							    {
							    	String strResult="";					    	
							    	String urlString=((GetContentEvent) event).getPath();

									HttpURLConnection conn = (HttpURLConnection) new URL(urlString).openConnection();
						        	// 設定Timeout時間
						        	conn.setConnectTimeout(30000);
						        	conn.setReadTimeout(30000);
						        	conn.setRequestMethod("POST");
						        	// Setup
						        	conn.setUseCaches (false); 
						        	conn.setDoOutput(true); 
						        	conn.setDoInput(true);
						        	OutputStream out = conn.getOutputStream();
						        	String strPostData = "device=android&ver="+((iiiApplication)mContext).VER +"&checkCode="+genCheckCode("mic"+((GetContentEvent) event).getContentId()) + "&content_id=" +((GetContentEvent) event).getContentId();
									out.write(strPostData.getBytes());
									out.close();
//									Log.d("ken", "strPostData" + strPostData);
						        	//当正确响应时处理数据
//						        	StringBuffer sb = new StringBuffer();
//						        	String readLine;
						        	BufferedReader responseReader;
						        	//处理响应流，必须与服务器响应流输出的编码一致
						        	
						        	responseReader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
					    			String line = null; 
					    			StringBuilder stringBuilder = new StringBuilder();
					    			while((line = responseReader.readLine()) != null) {
					    				stringBuilder.append(line);
					    			}
						        	strResult = stringBuilder.toString();
//						        	Log.d("ken", "GetContentEvent  "+strResult);
						        	conn.disconnect();
						        	
//						        	int result = new JSONObject(strResult).getInt("result");
//						        	String message = new JSONObject(strResult).getString("message"); 
//						        	int itemId = new JSONObject(strResult).getInt("item_id");
//						        	String itemName = new JSONObject(strResult).getString("item_name"); 
//						        	JSONArray jsonResponse = new JSONObject(strResult).getJSONArray("list");
							    	
							    	// test only
						        	try {
							        	data.setResult(new JSONObject(strResult).getInt("result"));
								    	data.setMessage(new JSONObject(strResult).getString("message"));
								    	data.setItemId(new JSONObject(strResult).getInt("item_id"));
								    	data.setCode(new JSONObject(strResult).getString("code"));
								    	data.setName(new JSONObject(strResult).getString("name"));
								    	data.setTotle(new JSONObject(strResult).getInt("total"));
								    	data.setRemain(new JSONObject(strResult).getInt("remain"));
								    	data.setHour(new JSONObject(strResult).getInt("hour"));
								    	data.setExpense(new JSONObject(strResult).getInt("expense"));
								    	data.setDateStart(new JSONObject(strResult).getLong("date_start"));
								    	data.setDateEnd(new JSONObject(strResult).getLong("date_end"));
								    	data.setTimeSlot(new JSONObject(strResult).getString("time_slot"));
								    	data.setTimeStart(new JSONObject(strResult).getString("time_start"));
								    	data.setTimeEnd(new JSONObject(strResult).getString("time_end"));
								    	data.setLocation(new JSONObject(strResult).getString("location"));
								    	data.setTel(new JSONObject(strResult).getString("tel"));
								    	data.setObject(new JSONObject(strResult).getString("object"));
								    	data.setObjective(new JSONObject(strResult).getString("objective"));
								    	data.setOutline(new JSONObject(strResult).getString("outline"));
								    	data.setIntrodution(new JSONObject(strResult).getString("introduction"));
								    	data.setRemark(new JSONObject(strResult).getString("remark"));
								    	data.setPic(new JSONObject(strResult).getString("pic"));
								    	data.setContentId(new JSONObject(strResult).getInt("content_id"));
									} catch (JSONException e) {
//							        	data.setResult(new JSONObject(strResult).getInt("result"));
//								    	data.setMessage(new JSONObject(strResult).getString("message"));
										data.setResult(000);
									}
							    	
							    	notifyResult(event, data, true, false);
							    }
							    catch (Exception e)
							    { 
							      	notifyResult(event, data, false, false);
							    }
							}
							
							/**預約課程event*/
							if (event instanceof UpdMakeEvent) {
								
								UpdMakeBean data = new UpdMakeBean();
							    try
							    {
							    	String strResult="";					    	
							    	String urlString=((UpdMakeEvent) event).getPath();

									HttpURLConnection conn = (HttpURLConnection) new URL(urlString).openConnection();
						        	// 設定Timeout時間
						        	conn.setConnectTimeout(30000);
						        	conn.setReadTimeout(30000);
						        	conn.setRequestMethod("POST");
						        	// Setup
						        	conn.setUseCaches (false); 
						        	conn.setDoOutput(true); 
						        	conn.setDoInput(true);
						        	OutputStream out = conn.getOutputStream();
						        	String strPostData = 	 "device=android" 
						        							+"&ver="		+((iiiApplication)mContext).VER 
						        							+"&checkCode="	+genCheckCode("mic"+((UpdMakeEvent) event).getContentId()) 
						        							+"&content_id="	+((UpdMakeEvent) event).getContentId()
						        							+"&token="	+((iiiApplication)mContext).DEVICE_TOKEN
						        							+"&name=" 		+((UpdMakeEvent) event).getName()
						        							+"&member_id=" 	+((UpdMakeEvent) event).getMemberId()
						        							+"&email=" 		+((UpdMakeEvent) event).getEmail()
						        							+"&tel=" 		+((UpdMakeEvent) event).getTel()
						        							+"&fax=" 		+((UpdMakeEvent) event).getFax()
						        							+"&addr=" 		+((UpdMakeEvent) event).getaddr()
						        							+"&remark=" 	+((UpdMakeEvent) event).getRemak();
						        							
									out.write(strPostData.getBytes());
									out.close();
//									Log.d("ken", "strPostData " + strPostData);
						        	//当正确响应时处理数据
//						        	StringBuffer sb = new StringBuffer();
//						        	String readLine;
						        	BufferedReader responseReader;
						        	//处理响应流，必须与服务器响应流输出的编码一致
						        	
						        	responseReader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
					    			String line = null; 
					    			StringBuilder stringBuilder = new StringBuilder();
					    			while((line = responseReader.readLine()) != null) {
					    				stringBuilder.append(line);
					    			}
						        	strResult = stringBuilder.toString();
//						        	Log.d("ken", "UpdMakeEvent  "+strResult);
						        	conn.disconnect();
							    	
							    	// test only
							    	data.setResult(new JSONObject(strResult).getInt("result"));
							    	data.setMessage(new JSONObject(strResult).getString("message"));
							    	
							    	notifyResult(event, data, true, false);
							    }
							    catch (Exception e)
							    { 
							      	notifyResult(event, data, false, false);
							    }
							}
							
							/**預約記錄查詢event*/
							if (event instanceof GetMakeEvent) {
								
								List<GetMakeBean> data = new ArrayList<GetMakeBean>();
								
								GetMakeBean temp1 = new GetMakeBean();
				    			temp1.setMakeId(123);
				    			temp1.setContentId(123);
				    			temp1.setContentName("內容1");
				    			temp1.setItemId(123);
				    			temp1.setItemName("系列2");
				    			temp1.setContentCode("123");
				    			temp1.setStatus(1);
				    			temp1.setMakeTime(1294567890);
				    			data.add(temp1);
				    			
				    			GetMakeBean temp2 = new GetMakeBean();
				    			temp2.setMakeId(123);
				    			temp2.setContentId(123);
				    			temp2.setContentName("內容1");
				    			temp2.setItemId(123);
				    			temp2.setItemName("系列1");
				    			temp2.setContentCode("123");
				    			temp2.setStatus(0);
				    			temp2.setMakeTime(1294567890);
				    			data.add(temp2);
								
							    try
							    {
							    	String strResult="";					    	
							    	String urlString=((GetMakeEvent) event).getPath();
//
									HttpURLConnection conn = (HttpURLConnection) new URL(urlString).openConnection();
						        	// 設定Timeout時間
						        	conn.setConnectTimeout(30000);
						        	conn.setReadTimeout(30000);
						        	conn.setRequestMethod("POST");
						        	// Setup
						        	conn.setUseCaches (false); 
						        	conn.setDoOutput(true); 
						        	conn.setDoInput(true);
						        	OutputStream out = conn.getOutputStream();
						        	String strPostData = 	 "device=android" 
						        							+"&ver="		+((iiiApplication)mContext).VER 
						        							+"&checkCode="	+genCheckCode("mic"+((iiiApplication)mContext).DEVICE_TOKEN) 
						        							+"&token="	+((iiiApplication)mContext).DEVICE_TOKEN;
						        							
									out.write(strPostData.getBytes());
									out.close();
//									Log.d("ken", "strPostData " + strPostData);
						        	//当正确响应时处理数据
//						        	StringBuffer sb = new StringBuffer();
//						        	String readLine;
						        	BufferedReader responseReader;
						        	//处理响应流，必须与服务器响应流输出的编码一致
						        	
						        	responseReader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
					    			String line = null; 
					    			StringBuilder stringBuilder = new StringBuilder();
					    			while((line = responseReader.readLine()) != null) {
					    				stringBuilder.append(line);
					    			}
						        	strResult = stringBuilder.toString();
//						        	Log.d("ken", "GetMakeEvent  "+strResult);
						        	int result = new JSONObject(strResult).getInt("result");
						        	String message = new JSONObject(strResult).getString("message"); 
//						        	int itemId = new JSONObject(strResult).getInt("item_id");
//						        	String itemName = new JSONObject(strResult).getString("item_name"); 
						        	JSONArray jsonResponse = new JSONObject(strResult).getJSONArray("list");
						        	// test only
						        	for (int i = 0; i < jsonResponse.length(); i++) {
						        		JSONObject jsonObj = (JSONObject)jsonResponse.opt(i);
						        		GetMakeBean temp = new GetMakeBean();
						        		temp.setMessage(message);
						    			temp.setResult(result);
						    			temp.setMakeId(jsonObj.getInt("make_id"));
						    			temp.setContentId(jsonObj.getInt("content_id"));
						    			temp.setContentName(jsonObj.getString("content_name"));
						    			temp.setItemId(jsonObj.getInt("item_id"));
						    			temp.setItemName(jsonObj.getString("item_name"));
						    			temp.setContentCode(jsonObj.getString("content_code"));
						    			temp.setStatus(jsonObj.getInt("check_status"));
						    			temp.setMakeTime(jsonObj.getLong("make_time"));
						    			data.add(temp);
						        	}
							    	
							    	notifyResult(event, data, true, false);
							    }
							    catch (Exception e)
							    { 
							      	notifyResult(event, data, false, false);
							    }
							}
							
							/**隱藏預約記錄event*/
							if (event instanceof HideMakeExpireEvent) {
								
								HideMakeExpireBean data = new HideMakeExpireBean();
							    try
							    {
							    	String strResult="";					    	
							    	String urlString=((HideMakeExpireEvent) event).getPath();

									HttpURLConnection conn = (HttpURLConnection) new URL(urlString).openConnection();
						        	// 設定Timeout時間
						        	conn.setConnectTimeout(30000);
						        	conn.setReadTimeout(30000);
						        	conn.setRequestMethod("POST");
						        	// Setup
						        	conn.setUseCaches (false); 
						        	conn.setDoOutput(true); 
						        	conn.setDoInput(true);
						        	OutputStream out = conn.getOutputStream();
						        	String strPostData = 	 "device=android" 
						        							+"&ver="		+((iiiApplication)mContext).VER 
						        							+"&checkCode="	+genCheckCode("mic"+((iiiApplication)mContext).DEVICE_TOKEN) 
						        							+"&make_id="	+((HideMakeExpireEvent) event).getMakeId()
						        							+"&token="		+((iiiApplication)mContext).DEVICE_TOKEN;
						        							
									out.write(strPostData.getBytes());
									out.close();
//									Log.d("ken", "strPostData " + strPostData);
						        	//当正确响应时处理数据
//						        	StringBuffer sb = new StringBuffer();
//						        	String readLine;
						        	BufferedReader responseReader;
						        	//处理响应流，必须与服务器响应流输出的编码一致
						        	
						        	responseReader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
					    			String line = null; 
					    			StringBuilder stringBuilder = new StringBuilder();
					    			while((line = responseReader.readLine()) != null) {
					    				stringBuilder.append(line);
					    			}
						        	strResult = stringBuilder.toString();
//						        	Log.d("ken", "HideMakeExpireEvent  "+strResult);
						        	conn.disconnect();
							    	// test only
							    	data.setResult(new JSONObject(strResult).getInt("result"));
							    	data.setMessage(new JSONObject(strResult).getString("message"));
							    	
							    	notifyResult(event, data, true, false);
							    }
							    catch (Exception e)
							    { 
							      	notifyResult(event, data, false, false);
							    }
							}
							
							/**搜尋課程內容清單event*/
							if (event instanceof SearchContentEvent) {
								
								List<SearchContentBean> data = new ArrayList<SearchContentBean>();
							    try
							    {
							    	String strResult="";					    	
							    	String urlString=((SearchContentEvent) event).getPath();

										HttpURLConnection conn = (HttpURLConnection) new URL(urlString).openConnection();
							        	// 設定Timeout時間
							        	conn.setConnectTimeout(30000);
							        	conn.setReadTimeout(30000);
							        	conn.setRequestMethod("POST");
							        	// Setup
							        	conn.setUseCaches (false); 
							        	conn.setDoOutput(true); 
							        	conn.setDoInput(true);
							        	OutputStream out = conn.getOutputStream();
							        	String strPostData = 	 "device=android" 
			        											+"&ver="		+((iiiApplication)mContext).VER 
			        											+"&checkCode="	+genCheckCode("mic"+((iiiApplication)mContext).DEVICE_TOKEN) 
			        											+"&date="	+((SearchContentEvent) event).getDate()
			        											+"&time="	+((SearchContentEvent) event).getTime()
			        											+"&slot="	+((SearchContentEvent) event).getSlot();
										out.write(strPostData.getBytes());
										out.close();
//										Log.d("ken", "strPostData" + strPostData);
							        	//当正确响应时处理数据
//							        	StringBuffer sb = new StringBuffer();
//							        	String readLine;
							        	BufferedReader responseReader;
							        	//处理响应流，必须与服务器响应流输出的编码一致
							        	
							        	responseReader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
						    			String line = null; 
						    			StringBuilder stringBuilder = new StringBuilder();
						    			while((line = responseReader.readLine()) != null) {
						    				stringBuilder.append(line);
						    			}
							        	strResult = stringBuilder.toString();
//							        	Log.d("ken", "SearchContentEvent  "+strResult);
							        	conn.disconnect();
							        	
							        	int result = new JSONObject(strResult).getInt("result");
							        	String message = new JSONObject(strResult).getString("message"); 
							        	JSONArray jsonResponse = new JSONObject(strResult).getJSONArray("list");
							    	
							    	for (int i = 0; i < jsonResponse.length(); i++) {
							    		JSONObject jsonObj = (JSONObject)jsonResponse.opt(i);
							    		SearchContentBean temp = new SearchContentBean();
							    		temp.setMessage(message);
							    		temp.setResult(result);
							    		temp.setItemId(jsonObj.getInt("item_id"));
							    		temp.setContentId(jsonObj.getInt("content_id"));
							    		temp.setDateStart(jsonObj.getLong("date_start"));
							    		temp.setDateEnd(jsonObj.getLong("date_end"));
							    		temp.setRemain(jsonObj.getInt("remain"));
							    		temp.setItemName(jsonObj.getString("item_name"));
							    		temp.setContentName(jsonObj.getString("content_name"));
							    		temp.setContentCode(jsonObj.getString("content_code"));
							    		data.add(temp);
									}
							    	
							    	notifyResult(event, data, true, false);
							    }
							    catch (Exception e)
							    { 
							      	notifyResult(event, data, false, false);
							    }
							}
							
							/**取得手機辨識碼event*/
							if (event instanceof GetTokenEvent) {
								
								GetTokenBean data = new GetTokenBean();
							    try
							    {
							    	String strResult="";					    	
							    	String urlString=((GetTokenEvent) event).getPath();

									HttpURLConnection conn = (HttpURLConnection) new URL(urlString).openConnection();
						        	// 設定Timeout時間
						        	conn.setConnectTimeout(30000);
						        	conn.setReadTimeout(30000);
						        	conn.setRequestMethod("POST");
						        	// Setup
						        	conn.setUseCaches (false); 
						        	conn.setDoOutput(true); 
						        	conn.setDoInput(true);
						        	OutputStream out = conn.getOutputStream();
						        	String strPostData = 	 "device=android" 
						        							+"&ver="		+((iiiApplication)mContext).VER 
						        							+"&checkCode="	+genCheckCode("mic");
						        							
									out.write(strPostData.getBytes());
									out.close();
//									Log.d("ken", "strPostData " + strPostData);
						        	//当正确响应时处理数据
//						        	StringBuffer sb = new StringBuffer();
//						        	String readLine;
						        	BufferedReader responseReader;
						        	//处理响应流，必须与服务器响应流输出的编码一致
						        	
						        	responseReader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
					    			String line = null; 
					    			StringBuilder stringBuilder = new StringBuilder();
					    			while((line = responseReader.readLine()) != null) {
					    				stringBuilder.append(line);
					    			}
						        	strResult = stringBuilder.toString();
//						        	Log.d("ken", "GetTokenEvent  "+strResult);
						        	conn.disconnect();
							    	// test only
							    	data.setResult(new JSONObject(strResult).getInt("result"));
							    	data.setMessage(new JSONObject(strResult).getString("message"));
							    	data.setToken(new JSONObject(strResult).getString("token"));
							    	
							    	notifyResult(event, data, true, false);
							    }
							    catch (Exception e)
							    { 
							      	notifyResult(event, data, false, false);
							    }
							}
							
							/**搜尋條件欄位資料event*/
							if (event instanceof SearchConditionedEvent) {
								
								SearchConditionedBean data = new SearchConditionedBean();
							    try
							    {
							    	String strResult="";					    	
							    	String urlString=((SearchConditionedEvent) event).getPath();

									HttpURLConnection conn = (HttpURLConnection) new URL(urlString).openConnection();
						        	// 設定Timeout時間
						        	conn.setConnectTimeout(30000);
						        	conn.setReadTimeout(30000);
						        	conn.setRequestMethod("POST");
						        	// Setup
						        	conn.setUseCaches (false); 
						        	conn.setDoOutput(true); 
						        	conn.setDoInput(true);
						        	OutputStream out = conn.getOutputStream();
						        	String strPostData = 	 "device=android" 
						        							+"&ver="		+((iiiApplication)mContext).VER 
						        							+"&checkCode="	+genCheckCode("mic");
						        							
									out.write(strPostData.getBytes());
									out.close();
//									Log.d("ken", "strPostData " + strPostData);
						        	//当正确响应时处理数据
//						        	StringBuffer sb = new StringBuffer();
//						        	String readLine;
						        	BufferedReader responseReader;
						        	//处理响应流，必须与服务器响应流输出的编码一致
						        	
						        	responseReader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
					    			String line = null; 
					    			StringBuilder stringBuilder = new StringBuilder();
					    			while((line = responseReader.readLine()) != null) {
					    				stringBuilder.append(line);
					    			}
						        	strResult = stringBuilder.toString();
//						        	Log.d("ken", "SearchConditionedEvent  "+strResult);
						        	conn.disconnect();
							    	// test only
							    	JSONArray date = new JSONObject(strResult).getJSONArray("date");
							    	List<String> dateList = new ArrayList<String>();
							    	for (int i = 0; i < date.length(); i++) {
							    		dateList.add(date.optString(i));
									}
							    	JSONArray slot = new JSONObject(strResult).getJSONArray("slot");
							    	List<String> slotList = new ArrayList<String>();
							    	for (int i = 0; i < slot.length(); i++) {
							    		slotList.add(slot.optString(i));
									}
							    	JSONArray time = new JSONObject(strResult).getJSONArray("time");
							    	List<String> timeList = new ArrayList<String>();
							    	for (int i = 0; i < time.length(); i++) {
							    		timeList.add(time.optString(i));
									}
							    	data.setResult(new JSONObject(strResult).getInt("result"));
							    	data.setMessage(new JSONObject(strResult).getString("message"));
							    	data.setDateList(dateList);
							    	data.setSlotList(slotList);
							    	data.setTimeList(timeList);
							    	notifyResult(event, data, true, false);
							    }
							    catch (Exception e)
							    { 
							    	try {
							    		String strResult = mContext.getString(R.string.test);
								    	// test only
								    	JSONArray date = new JSONObject(strResult).getJSONArray("date");
								    	List<String> dateList = new ArrayList<String>();
								    	for (int i = 0; i < date.length(); i++) {
								    		dateList.add(date.optString(i));
										}
								    	JSONArray slot = new JSONObject(strResult).getJSONArray("slot");
								    	List<String> slotList = new ArrayList<String>();
								    	for (int i = 0; i < slot.length(); i++) {
								    		slotList.add(slot.optString(i));
										}
								    	JSONArray time = new JSONObject(strResult).getJSONArray("time");
								    	List<String> timeList = new ArrayList<String>();
								    	for (int i = 0; i < time.length(); i++) {
								    		timeList.add(time.optString(i));
										}
								    	data.setResult(new JSONObject(strResult).getInt("result"));
								    	data.setMessage(new JSONObject(strResult).getString("message"));
								    	data.setDateList(dateList);
								    	data.setSlotList(slotList);
								    	data.setTimeList(timeList);
								    	notifyResult(event, data, true, false);
									} catch (Exception e2) {
										// TODO: handle exception
									}
							    	
//							      	notifyResult(event, data, false, false);
							    }
							}
							
							/**訊息快遞event*/
							if (event instanceof GetMsgEvent) {
								
								List<GetMsgBean> data = new ArrayList<GetMsgBean>();
								
								GetMsgBean temp1 = new GetMsgBean();
					    		temp1.setMsgId(123);
					    		temp1.setName("訊息1");
					    		temp1.setContent("訊息內容");
					    		temp1.setPic("http://upload.wikimedia.org/wikipedia/commons/thumb/0/0f/Grosser_Panda.JPG/320px-Grosser_Panda.JPG");
					    		temp1.setTime(1294567890);
					    		data.add(temp1);
					    		GetMsgBean temp2 = new GetMsgBean();
					    		temp2.setMsgId(123);
					    		temp2.setName("訊息2");
					    		temp2.setContent("訊息內容");
					    		temp2.setPic("http://upload.wikimedia.org/wikipedia/commons/thumb/0/0f/Grosser_Panda.JPG/320px-Grosser_Panda.JPG");
					    		temp2.setTime(1294567890);
					    		data.add(temp1);
					    		
							    try
							    {
							    	String strResult="";					    	
							    	String urlString=((GetMsgEvent) event).getPath();

										HttpURLConnection conn = (HttpURLConnection) new URL(urlString).openConnection();
							        	// 設定Timeout時間
							        	conn.setConnectTimeout(30000);
							        	conn.setReadTimeout(30000);
							        	conn.setRequestMethod("POST");
							        	// Setup
							        	conn.setUseCaches (false); 
							        	conn.setDoOutput(true); 
							        	conn.setDoInput(true);
							        	OutputStream out = conn.getOutputStream();
							        	String strPostData = 	 "device=android" 
							        							+"&time=0"
			        											+"&ver="		+((iiiApplication)mContext).VER 
			        											+"&checkCode="	+genCheckCode("mic");
										out.write(strPostData.getBytes());
										out.close();
//										Log.d("ken", "strPostData" + strPostData);
							        	//当正确响应时处理数据
//							        	StringBuffer sb = new StringBuffer();
//							        	String readLine;
							        	BufferedReader responseReader;
							        	//处理响应流，必须与服务器响应流输出的编码一致
							        	
							        	responseReader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
						    			String line = null; 
						    			StringBuilder stringBuilder = new StringBuilder();
						    			while((line = responseReader.readLine()) != null) {
						    				stringBuilder.append(line);
						    			}
							        	strResult = stringBuilder.toString();
//							        	Log.d("ken", "GetMsgEvent  "+strResult);
							        	conn.disconnect();
							        	
							        	int result = new JSONObject(strResult).getInt("result");
							        	String message = new JSONObject(strResult).getString("message"); 
							        	JSONArray jsonResponse = new JSONObject(strResult).getJSONArray("list");
							    	
							    	for (int i = 0; i < jsonResponse.length(); i++) {
							    		JSONObject jsonObj = (JSONObject)jsonResponse.opt(i);
							    		GetMsgBean temp = new GetMsgBean();
							    		temp.setMessage(message);
							    		temp.setResult(result);
							    		temp.setMsgId(jsonObj.getInt("msg_id"));
							    		temp.setName(jsonObj.getString("name"));
							    		temp.setContent(jsonObj.getString("content"));
							    		temp.setPic(jsonObj.getString("pic"));
							    		temp.setTime(jsonObj.getLong("time"));
							    		data.add(temp);
									}
							    	
							    	notifyResult(event, data, true, false);
							    }
							    catch (Exception e)
							    { 
							      	notifyResult(event, data, false, false);
							    }
							}
							
							
							/**訊息快遞-新訊息數量event*/
							if (event instanceof getMsgCountEvent) {
								
								getMsgCountBean data = new getMsgCountBean();
							    try
							    {
							    	String strResult="";					    	
							    	String urlString=((getMsgCountEvent) event).getPath();

										HttpURLConnection conn = (HttpURLConnection) new URL(urlString).openConnection();
							        	// 設定Timeout時間
							        	conn.setConnectTimeout(30000);
							        	conn.setReadTimeout(30000);
							        	conn.setRequestMethod("POST");
							        	// Setup
							        	conn.setUseCaches (false); 
							        	conn.setDoOutput(true); 
							        	conn.setDoInput(true);
							        	OutputStream out = conn.getOutputStream();
							        	String strPostData = 	 "device=android" 
							        							+"&time="		+getMsgTime()
			        											+"&ver="		+((iiiApplication)mContext).VER 
			        											+"&checkCode="	+genCheckCode("mic");
										out.write(strPostData.getBytes());
										out.close();
//										Log.d("ken", "strPostData" + strPostData);
							        	//当正确响应时处理数据
//							        	StringBuffer sb = new StringBuffer();
//							        	String readLine;
							        	BufferedReader responseReader;
							        	//处理响应流，必须与服务器响应流输出的编码一致
							        	
							        	responseReader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
						    			String line = null; 
						    			StringBuilder stringBuilder = new StringBuilder();
						    			while((line = responseReader.readLine()) != null) {
						    				stringBuilder.append(line);
						    			}
							        	strResult = stringBuilder.toString();
//							        	Log.d("ken", "getMsgCountEvent  "+strResult);
							        	conn.disconnect();
							        	
							        	int result = new JSONObject(strResult).getInt("result");
							        	String message = new JSONObject(strResult).getString("message"); 
							        	int count = new JSONObject(strResult).getInt("count");
							        	data.setResult(result);
							        	data.setMessage(message);
							        	data.setCount(count);
							        	
							    	notifyResult(event, data, true, false);
							    }
							    catch (Exception e)
							    { 
							      	notifyResult(event, data, false, false);
							    }
							}
							
//							if (event instanceof GetURLBitmapEvent) {
////								Bitmap[] bitmaps = new Bitmap [((GetURLBitmapEvent) event).getList().size()];
////								for (int i = 0; i < bitmaps.length; i++) {
////									try {
////										URL url = new URL(((GetURLBitmapEvent) event).getList().get(i).getImg());
////										URLConnection conn = url.openConnection();
////										conn.connect();
////										InputStream isCover = conn.getInputStream();
////										Bitmap bmpCover = BitmapFactory.decodeStream(isCover);
////										isCover.close();
////										bitmaps[i] = bmpCover;
////									} catch (Exception e) {
////										bitmaps[i] = null;
////									}
////								}
////								notifyResult(event, bitmaps, true, false);
//							}
						}
					}
				}
			}
		});	
	}
		
	void executeSubEvents(Event event) {
		List<Event> subEvents = event.getSubEvents();
		for(int i = 0; i < subEvents.size(); i++) {
			// execute本來就已經Thread化惹
			execute(subEvents.get(i));
		}
	}
											   /****/
	void notifyResult(final Event event, final Object connectionBean, boolean isSuccess, boolean isDownload) {
		// 執行黏在Event上的callback
		List<IEventCallback> callbacks = event.getCallbacks();
		for(int i = 0; i < callbacks.size(); i++) {
			final IEventCallback callback = callbacks.get(i);
			mGeneralPool.execute(new Runnable() {
				public void run() {
					callback.result(event, connectionBean);
				}
			});
		}
		
		mGeneralPool.execute(new Runnable() {
			public void run() {
				synchronized(mExecutingMap) {
				 	// 解除Executing裡的這個事件
					mExecutingMap.remove(event.getSignature());
				}
			}
		});
		
		if(isSuccess || isDownload) {
			// 通知所有有註冊這個事件的人
			synchronized(mListenerMap) {
				String signuture = event.getSignature();
				callbacks = mListenerMap.get(signuture);
				if(callbacks != null) {
					for(int i = 0; i < callbacks.size(); i++) {
						final IEventCallback callback = callbacks.get(i);
						mGeneralPool.execute(new Runnable() {
							public void run() {
								callback.result(event, connectionBean);
							}
						});
					}
				}
				
				// 執行SubEvents
				executeSubEvents(event);
			}
		}
	}	
	
	void notifyProgress(final Event event, final int progress, final String tmpPath) {
		// 執行黏在Event上的callback
		List<IEventCallback> callbacks = event.getCallbacks();
		for(int i = 0; i < callbacks.size(); i++) {
			final IEventCallback callback = callbacks.get(i);
			mGeneralPool.execute(new Runnable() {
				public void run() {
					callback.progress(event, progress, tmpPath);
				}
			});
		}
		
		// 通知所有有註冊這個事件的人
		mGeneralPool.execute(new Runnable() {
			public void run() {
				synchronized(mListenerMap) {
					List<IEventCallback> callbacks = mListenerMap.get(event.getSignature());
					if(callbacks != null) {
						for(int i = 0; i < callbacks.size(); i++) {
							final IEventCallback callback = callbacks.get(i);
							mGeneralPool.execute(new Runnable() {
								public void run() {
									callback.progress(event, progress, tmpPath);
								}
							});
						}
					}
				}
			}
		});
	}
	
	
	
	public String genCheckCode(String sn) {
		StringBuilder checkCode = new StringBuilder();
		// 設定時間格式&時區
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmm");
		format.setTimeZone(TimeZone.getTimeZone("GMT+16:00"));
		// 設定MD5
		MD5 md5 = new MD5();
		try {
//			Calendar calendar =Calendar.getInstance();
//			String fullUrl = sn + format.format(calendar.getTime());
//			format.setTimeZone(TimeZone.getTimeZone("GMT"));
//			Date date = new Date(new Date().getTime() + EventManager.getInstance().getServerTimeOffset()); // 要加上ServerOffset
			long localTimeInGMT = new Date().getTime() + (new Date().getTimezoneOffset()*60*1000);
			Date date = new Date(localTimeInGMT + getServerTimeOffset()); // 要加上ServerOffset
			 
			String fullUrl = sn + format.format(date); 
//			Log.d("ken", "localTimeInGMT"+format.format(date)+"getServerTimeOffset " + getServerTimeOffset());
			md5.Update(fullUrl, null);
			byte[] hash = md5.asHex().getBytes();
			// 取出特定的字元
			
			for (int i = 0; i < hash.length; i++) {
				checkCode.append((char)hash[i]);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		// 回傳
		return checkCode.toString();
	}
	
	public String genCheckCodeForHead(String url) {
		StringBuilder checkCode = new StringBuilder();
		// 設定時間格式&時區
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmm");
		format.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
		// 設定MD5
		MD5 md5 = new MD5();
		try {
//			format.setTimeZone(TimeZone.getTimeZone("GMT"));
//			Date date = new Date(new Date().getTime() + EventManager.getInstance().getServerTimeOffset()); // 要加上ServerOffset
			long localTimeInGMT = new Date().getTime() + (new Date().getTimezoneOffset()*60*1000);
			Date date = new Date(localTimeInGMT + getServerTimeOffset()); // 要加上ServerOffset
			String fullUrl = url + format.format(date); 
			md5.Update(fullUrl, null);
			byte[] hash = md5.asHex().getBytes();
			// 取出特定的字元
			checkCode.append((char)hash[4]);
			checkCode.append((char)hash[11]);
			checkCode.append((char)hash[2]);
			checkCode.append((char)hash[6]);
			checkCode.append((char)hash[8]);
			checkCode.append((char)hash[19]);
			checkCode.append((char)hash[12]);
			checkCode.append((char)hash[14]);
			checkCode.append((char)hash[6]);
			checkCode.append((char)hash[21]);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		// 回傳
		return checkCode.toString();
	}
	
	
	/*********************
	 * Private Functions *
	 *********************/
	
	public String getCookie() {
		return mContext.getSharedPreferences("iiicoursecenter", Context.MODE_PRIVATE).getString("cookie", null);
	}
	
	public void setCookie(String cookie) {
		if(cookie != null && !cookie.equals("")) mContext.getSharedPreferences("iiicoursecenter", Context.MODE_PRIVATE).edit().putString("cookie", cookie).commit();
		else mContext.getSharedPreferences("iiicoursecenter", Context.MODE_PRIVATE).edit().remove("cookie").commit();
	}
	
	public long getServerTimeOffset() {
		return mContext.getSharedPreferences("iiicoursecenter", Context.MODE_PRIVATE).getLong("server_time_offset", 0);
	}
	
	public void setServerTimeOffset(long offset) {
		mContext.getSharedPreferences("iiicoursecenter", Context.MODE_PRIVATE).edit().putLong("server_time_offset", offset).commit();
	}
	
	public String getName() {
		return mContext.getSharedPreferences("iiicoursecenter", Context.MODE_PRIVATE).getString("name", "");
	}
	
	public void setName(String name) {
		mContext.getSharedPreferences("iiicoursecenter", Context.MODE_PRIVATE).edit().putString("name", name).commit();
	}
	
	public String getRemark() {
		return mContext.getSharedPreferences("iiicoursecenter", Context.MODE_PRIVATE).getString("remark", "");
	}
	
	public void setRemark(String remark) {
		mContext.getSharedPreferences("iiicoursecenter", Context.MODE_PRIVATE).edit().putString("remark", remark).commit();
	}
	
	public String getMemberId() {
		return mContext.getSharedPreferences("iiicoursecenter", Context.MODE_PRIVATE).getString("memberId", "");
	}
	
	public void setMemberId(String memberId) {
		mContext.getSharedPreferences("iiicoursecenter", Context.MODE_PRIVATE).edit().putString("memberId", memberId).commit();
	}
	
	public String getEmail() {
		return mContext.getSharedPreferences("iiicoursecenter", Context.MODE_PRIVATE).getString("email", "");
	}
	
	public void setEmail(String email) {
		mContext.getSharedPreferences("iiicoursecenter", Context.MODE_PRIVATE).edit().putString("email", email).commit();
	}
	
	public String getTel() {
		return mContext.getSharedPreferences("iiicoursecenter", Context.MODE_PRIVATE).getString("tel", "");
	}
	
	public void setTel(String tel) {
		mContext.getSharedPreferences("iiicoursecenter", Context.MODE_PRIVATE).edit().putString("tel", tel).commit();
	}
	
	public String getFax() {
		return mContext.getSharedPreferences("iiicoursecenter", Context.MODE_PRIVATE).getString("fax", "");
	}
	
	public void setFax(String fax) {
		mContext.getSharedPreferences("iiicoursecenter", Context.MODE_PRIVATE).edit().putString("fax", fax).commit();
	}
	
	public String getAddr() {
		return mContext.getSharedPreferences("iiicoursecenter", Context.MODE_PRIVATE).getString("addr", "");
	}
	
	public void setAddr(String addr) {
		mContext.getSharedPreferences("iiicoursecenter", Context.MODE_PRIVATE).edit().putString("addr", addr).commit();
	}
	
	public String getToken() {
		return mContext.getSharedPreferences("iiicoursecenter", Context.MODE_PRIVATE).getString("token", "null");
	}
	
	public void setToken(String token) {
		mContext.getSharedPreferences("iiicoursecenter", Context.MODE_PRIVATE).edit().putString("token", token).commit();
	}
	
	public long getMsgTime() {
		return mContext.getSharedPreferences("iiicoursecenter", Context.MODE_PRIVATE).getLong("msgcount", 0);
	}
	
	public void setMsgTime(long msgtime) {
		mContext.getSharedPreferences("iiicoursecenter", Context.MODE_PRIVATE).edit().putLong("msgcount", msgtime).commit();
	}
	
	public long getMsgIdRead(int msgId ) {
		return mContext.getSharedPreferences("iiicoursecenter", Context.MODE_PRIVATE).getLong("msgidtime"+msgId, 0);
	}
	
	public void setMsgIdRead(int msgId ,long time) {
		mContext.getSharedPreferences("iiicoursecenter", Context.MODE_PRIVATE).edit().putLong("msgidtime"+msgId, time).commit();
	}
	
}
